package conf

import (
	"gitee.com/saxon134/go-utils/saData"
	"gitee.com/saxon134/go-utils/saHttp"
	"gopkg.in/yaml.v2"
	"os"
	"strings"
)

var Conf *ModelConf
var _conf map[string]interface{}

type ModelConf struct {
	Name string
	Mode string

	Sysmain struct {
		Url        string
		ClientRoot string
		Secret     string
		PingSecond int
	}

	Http struct {
		Host       string //http地址，默认不配置
		Port       int    //http端口
		JwtSecret  string
		SignSecret string
	}

	MySql struct {
		Host string
		User string
		Pass string
		Db   string
	}

	Redis struct {
		Host string
		Pass string
	}

	Oss struct {
		EndPoint        string
		AccessKeyId     string
		AccessKeySecret string

		Host   string
		Bucket string
	}
}

func Init() *ModelConf {
	if Conf == nil {
		Conf = new(ModelConf)

		f_n := "./config.yaml"
		yamlData, err := os.ReadFile(f_n)
		if err != nil {
			panic("配置文件路径有误")
		}

		err = yaml.Unmarshal(yamlData, Conf)
		if err != nil {
			panic("配置文件信息有误")
		}

		err = yaml.Unmarshal(yamlData, &_conf)
		if err != nil {
			panic("配置文件信息有误")
		}
	}

	if Conf.Http.Host == "" {
		ary, err := saHttp.GetLocalIP()
		if len(ary) == 0 {
			panic("get local ip error: " + err.Error())
		}
		Conf.Http.Host = ary[0]
	}
	return Conf
}

// Get key支持 a:b:c形式
func Get(key string) string {
	ary := strings.Split(key, ":")
	var e error
	var c = _conf
	var s string
	for i, k := range ary {
		if i+1 < len(ary) {
			if c != nil {
				c, e = saData.ToMap(c[k])
				if e != nil {
					return ""
				}
			}
		} else {
			s, e = saData.ToStr(c[k])
			if e != nil {
				return ""
			}
		}
	}
	return s
}
